<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>发货计划信息</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body class="layui-anim layui-anim-up">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>应付管理</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<div class="layui-input-block" style="width:200px;margin-left: 0px;margin-top: 0px;">
							<select class="layui-input" name="keyword01" id="keyword01" lay-filter="forwardingunit">
								<option value="">请选择项目</option>
								<c:forEach items="${items}" var="item">
									<option value="${item.id}">${item.itemName}-${item.itemNumber}</option>
								</c:forEach>
							</select>
						</div>
					</td>
					<td>
						<div class="layui-input-block" style="width:200px;margin-left: 0px;margin-top: 0px;">
							<select class="layui-input" name="keyword02" id="keyword02"  lay-filter="forwardingunit">
								<option value="">请选择付款方</option>
								<c:forEach items="${customers}" var="customer">
									<option value="${customer.id}">${customer.customer_name}-${customer.customer_num}</option>
								</c:forEach>
							</select>
						</div>
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon">&#xe615;</i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon"></i>新增</button>
			<button id="dels" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
      </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	  <table class="layui-hide" id="tableDetails1" lay-filter="tableDetails1"></table>
	</div>
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
		<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="addDetails">发票登记</a>
	</script>
	<script type="text/html" id="rowToolbarDetails">
		<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
	</script>

	<div id="addDivID" hidden="hidden">
		<form class="layui-form" id="addFormID">
			 <!-- id -->
			<input type="hidden" id="clientId" name="clientId" value="${customer_id}">
			<input type="hidden" id="id" name="id">
			<label class="layui-form-label">项目</label>
			<div class="layui-input-block" style="width:300px;margin-top:15px">
				<select class="layui-input" name="projectId" id="projectId" lay-verify="required">
					<option value="">请选择项目</option>
					<c:forEach items="${items}" var="item">
						<option value="${item.id}">${item.itemName}-${item.itemNumber}</option>
					</c:forEach>
				</select>
			</div>
			<span class="xing"></span> 
			<br>
			<label class="layui-form-label">金额</label></td>
			<input class="layui-input" id="money" name="money" style="width: 300px" lay-verify="money" placeholder="请输入金额">
			<span class="xing"></span>
			<br>
			<label class="layui-form-label">收款方</label>
			<div class="layui-input-block" style="width:300px;">
				<select class="layui-input" name="payClientId" id="payClientId" lay-verify="required">
					<option value="">请选择客户</option>
					<c:forEach items="${customers}" var="customer">
						<option value="${customer.id}">${customer.customer_name}-${customer.customer_num}</option>
					</c:forEach>
				</select>
			</div>
			<span class="xing"></span>
			<br>
			<label class="layui-form-label">备注</label></td>
			<input class="layui-input" id="remarks" name="remarks" style="width: 300px"  placeholder="请输入备注">
			<br>
			<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:140px;">提交</button>
			&emsp;&emsp;&emsp;&emsp;
			<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button></td>
			<!-- <button type="reset" class="layui-btn layui-btn-primary">重置</button> -->
		</form>
    </div>
	<div id="addDetailsDivID" hidden="hidden">
		<form class="layui-form" id="addDetailsFormID">
			 <!-- id -->
			<input type="hidden" id="payId" name="payId">
			<input type="hidden" id="did" name="id">
			<label class="layui-form-label">发票号</label>
			<input class="layui-input" id="invoiceNumber" name="invoiceNumber" style="width: 300px;margin-top:15px" lay-verify="only" placeholder="请输入发票号">
			<span class="xing"></span> 
			<br>
			<label class="layui-form-label">发票金额</label></td>
			<input class="layui-input" id="dmoney" name="money" style="width: 300px" lay-verify="money" placeholder="请输入发票金额">
			<span class="xing"></span>
			<br>
			<label class="layui-form-label">发票日期</label></td>
			<input class="layui-input" id="createDate" name="createDate" style="width: 300px" lay-verify="required" placeholder="请输入发票日期">
			<span class="xing"></span>
			<br>
			<label class="layui-form-label">税率</label></td>
			<div class="layui-input-block" style="width:300px;">
				<select class="layui-input" name="tax" id="tax" lay-verify="required">
					<option value="">请选择</option>
					<option>普票</option>
					<option>无票</option>
					<option>增票</option>
				</select>
			</div>
			<span class="xing"></span>
			<br>
			<label class="layui-form-label">付款方式</label>
			<div class="layui-input-block" style="width:300px;">
				<select class="layui-input" name="payType" id="payType" lay-verify="required">
					<option value="">请选择</option>
					<option>公户</option>
					<option>私户</option>
				</select>
			</div>
			<span class="xing"></span>
			<br>
			<button class="layui-btn layui-btn-blue" id="subBtn1" lay-submit lay-filter="addDetailsForm" style="margin-left:140px;">提交</button>
			&emsp;&emsp;&emsp;&emsp;
			<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button></td>
			<!-- <button type="reset" class="layui-btn layui-btn-primary">重置</button> -->
		</form>
    </div>

	<script type="text/javascript">
        var table;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			
			
			var laydate = layui.laydate;
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword01 = $.trim($("#keyword01").val());
	                var keyword02 = $.trim($("#keyword02").val());
					table.reload('tableList',{
						method:'get'
						,where:{
							projectId:keyword01
	                        ,payClientId:keyword02
						}
						,page: {
		                    curr: 1//重新从第 1 页开始
		                }
					});
				}
			}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			var clientId = $.trim($("#clientId").val());
			var url = '${pageContext.request.contextPath }/handle/list.do'
				url += '?clientId='+clientId
			table.render({
				elem: '#tableList'
				,url:url
				,toolbar: '#toolbar'
				,title: 'machineList'
				,limits:[10,20,30]
                ,defaultToolbar:['filter', 'print']
				,request: {   //如果无需自定义请求参数，可不加该参数
	                pageName: 'page' //页码的参数名称，默认：page
	                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
	            }
	            ,response: {   //如果无需自定义数据响应名称，可不加该参数
	                countName: 'total' //规定数据总数的字段名称，默认：count
	                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
	            }
				,cols: [
		                [{
		                    type: 'checkbox',
		                    fixed: 'left'
		                }, {
		                	field:'id',
		                	title:'序号', 
		                	sort: true,
		                	width: 60,
		                	type:'numbers',
		                	align:'center'
		                }, {
		                    field: 'id',
		                    title: 'id',
		                    hide:true //是否初始隐藏列，默认：false。layui 2.4.0 新增
		                } , {
		                    title: '项目名称',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.item !=null){
            	    				value = d.item.itemName
            	    			}
            	    			return value;
            	    		} 
		                } , {
		                    title: '项目编号',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.item !=null){
            	    				value = d.item.itemNumber
            	    			}
            	    			return value;
            	    		} 
		                } , {
		                    title: '项目说明',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.item !=null){
            	    				value = d.item.explain
            	    			}
            	    			return value;
            	    		} 
		                } , {
		                    field: 'money',
		                    title: '金额',
		                    align:'center',
		                } , {
		                    title: '收款方',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.kehuCustomer !=null){
            	    				value = d.kehuCustomer.customer_name
            	    			}
            	    			return value;
            	    		} 
		                /* } , {
		                    title: '客户',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.customer !=null){
            	    				value = d.customer.customer_name
            	    			}
            	    			return value;
            	    		} */ 
            	    	} , {
		                    field: 'remarks',
		                    title: '备注',
		                    align:'center',
		                }, {
		                    fixed: 'right',
		                    title:'操作',
		                    toolbar: '#rowToolbar',
		                    align:'center',
		                    unresize: true,
		                    width: 250 
		                }
		                ]
		               ]
				,page: true
				,done : function(){
	                $('th').css({
	                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                    //'font-size': 10,
	                })
	            }
			});
        	//表格
            table.render({
                elem: '#tableDetails1'
                ,url:'${pageContext.request.contextPath }/handleRegister/list.do?payId=-1'                
                ,title: '发货计划详细表'
                ,limits:[10,20,30]
                ,defaultToolbar:['filter', 'print']
                ,request: {   //如果无需自定义请求参数，可不加该参数
                    pageName: 'page' //页码的参数名称，默认：page
                    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                ,response: {   //如果无需自定义数据响应名称，可不加该参数
                    countName: 'total' //规定数据总数的字段名称，默认：count
                    ,dataName: 'rows' //规定数据列表的字段名称，默认：data
                } 
                ,cols: [
                    [{
                        field: 'id',
                        title: 'id',
                        hide:true //是否初始隐藏列，默认：false。layui 2.4.0 新增
                    }, {
                        field: 'payId',
                        title: '应付单id',
                        hide:true //是否初始隐藏列，默认：false。layui 2.4.0 新增
                    }, {
                    	field:'id',
                    	title:'序号', 
                    	sort: true,
                    	width: 60,
                    	type:'numbers',
                    	align:'center'
                    } , {
                    	field:'invoiceNumber',
                        title: '发票号',
                        align:'center',
                    }, {
                        field: 'money',
                        title: '发票金额',
                        align:'center',
                    }, {
                        field: 'createDate',
                        title: '发票日期',
                        align:'center',
                        templet: function(d){
	                    	var value = curentTime(d.createDate);
        	    			return value;
        	    		},
                    }, {
                        field: 'tax',
                        title: '税率',
                        align:'center',
                    }, {
                        field: 'payType',
                        title: '付款方式',
                        align:'center',
                    }, {
	                    fixed: 'right',
	                    title:'操作',
	                    toolbar: '#rowToolbarDetails',
	                    align:'center',
	                    unresize: true,
	                    width: 250 
                    }
                    ]]
                ,page: true
                ,done : function(){
	                $('th').css({
	                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                    //'font-size': 10,
	                })
	            } 
                ,height: 300
            });
        	
			
	        table.on('row(tableList)', function(obj){
	        	table.reload('tableDetails1',{
						url:'${pageContext.request.contextPath }/handleRegister/list.do?payId='+obj.data.id
						,method:'get'
						,page: {
			                curr: 1//重新从第 1 页开始
			            }
        	  	});
	        	
	        	if(obj.checked == true && obj.type == 'all'){
	                //点击全选
	                $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
	            }else if(obj.checked == false && obj.type == 'all'){
	                //点击全不选
	                $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
	            }else if(obj.checked == true && obj.type == 'one'){
	                //点击单行
	                if(obj.checked == true){
	                    obj.tr.addClass('layui-table-click');
	                }else{
	                    obj.tr.removeClass('layui-table-click');
	                }
	            }else if(obj.checked == false && obj.type == 'one'){
	                //点击全选之后点击单行
	                if(obj.tr.hasClass('layui-table-click')){
	                    obj.tr.removeClass('layui-table-click');
	                }
	            }
	        });
	        
			//监听行工具事件
			table.on('tool(tableList)', function(obj){
				var data = obj.data;
				//alert(data.id)
				var idArr = new Array();
				//单个删除
				if(obj.event === 'del'){
				  layer.confirm('确定删除吗？', function(index){
					var id = obj.data.id;
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/handle/delete.do',
						data:{ "ids" : id },
						success:function(data){
							if(data > 0){
								toastr.success("删除成功！");
								setTimeout(function(){
									location.reload();
								},1000);
							}else{
								toastr.warning("删除失败！");
								setTimeout(function(){
									location.reload();
								},1000);
							}
						}
					});
					layer.close(index);
				  });
				} else if(obj.event === 'edit'){
					layer.open({
					  type: 1 							//Page层类型
					  ,area: ['500px', '350px'] 	//宽  高
					  ,title: '编辑'
					  ,shade: 0.6 						//遮罩透明度
					  ,maxmin: true 					//允许全屏最小化
					  ,anim: 1 							//0-6的动画形式，-1不开启
					  ,content: $('#addDivID')
	                  ,end: function () {
	                      var formDiv = document.getElementById('addDivID');
	                      formDiv.style.display = '';
	                  }
	                  ,success: function(){
	                      $("#id").val(data.id)
	                      $("#projectId").val(data.projectId)
	                      $("#payClientId").val(data.payClientId)
	                      $("#money").val(data.money)
	                      $("#remarks").val(data.remarks)
	                      form.render();
	                    }
					});
				} else if(obj.event === 'addDetails'){
					layer.open({
					  type: 1 							//Page层类型
					  ,area: ['500px', '450px'] 	//宽  高
					  ,title: '付款登记'
					  ,shade: 0.6 						//遮罩透明度
					  ,maxmin: true 					//允许全屏最小化
					  ,anim: 1 							//0-6的动画形式，-1不开启
					  ,content: $('#addDetailsDivID')
	                  ,end: function () {
	                      var formDiv = document.getElementById('addDetailsDivID');
	                      formDiv.style.display = '';
	                  }
	                  ,success: function(){
	                      $("#did").val("")
	                      $("#invoiceNumber").val(curentTimeNumber())
	                      $("#payId").val(data.id)
	                      $("#dmoney").val("")
	                      $("#createDate").val(curentTime())
	                      $("#tax").val("")
	                      $("#payType").val("")
	                      form.render();
	                    }
					});
				}
			});
			//监听行工具事件
			table.on('tool(tableDetails1)', function(obj){
				var data = obj.data;
				//alert(data.id)
				var idArr = new Array();
				//单个删除
				if(obj.event === 'del'){
				  layer.confirm('确定删除吗？', function(index){
					var id = obj.data.id;
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/handleRegister/delete.do',
						data:{ "ids" : id },
						success:function(data){
							if(data > 0){
								toastr.success("删除成功！");
								setTimeout(function(){
									location.reload();
								},1000);
							}else{
								toastr.warning("删除失败！");
								setTimeout(function(){
									location.reload();
								},1000);
							}
						}
					});
					layer.close(index);
				  });
				} else if(obj.event === 'edit'){
					layer.open({
					  type: 1 							//Page层类型
					  ,area: ['500px', '450px'] 	//宽  高
					  ,title: '付款登记编辑'
					  ,shade: 0.6 						//遮罩透明度
					  ,maxmin: true 					//允许全屏最小化
					  ,anim: 1 							//0-6的动画形式，-1不开启
					  ,content: $('#addDetailsDivID')
	                  ,end: function () {
	                      var formDiv = document.getElementById('addDetailsDivID');
	                      formDiv.style.display = '';
	                  }
	                  ,success: function(){
	                      $("#did").val(data.id)
	                      $("#invoiceNumber").val(data.invoiceNumber)
	                      $("#payId").val(data.payId)
	                      $("#dmoney").val(data.money)
	                      $("#createDate").val(data.createDate)
	                      $("#tax").val(data.tax)
	                      $("#payType").val(data.payType)
	                      form.render();
	                    }
					});
				}
			});

			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				var index = layer.load(1, {
	        	    shade: [0.1,'#000'] //0.1透明度的背景
	        	});
				
				var formData = $("#addFormID").serialize();
				var title = "新增";
				var url = '${pageContext.request.contextPath}/handle/insert.do';
				var id = $.trim($("#id").val());
				if(id != "" && id != null && id != 'undefined'){
					var url = '${pageContext.request.contextPath}/handle/update.do';
					title = "修改";
				}
				$.ajax({
					url : url,
					data: formData,
					cache : false,
					type : "post",
					success: function (data) {
	                    if (data >= 1) {
	                        toastr.success(title+'成功');
	                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                            window.location.reload();
	                            $("#reset").click();
	                        },1000);
	                    } else {
	                        toastr.error(title+'失败');
	                    }
	                },
				})
				layer.close(index);
				return false;
			});
			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addDetailsForm)', function (data) {
				var index = layer.load(1, {
	        	    shade: [0.1,'#000'] //0.1透明度的背景
	        	});
				
				var formData = $("#addDetailsFormID").serialize();
				var title = "新增";
				var url = '${pageContext.request.contextPath}/handleRegister/insert.do';
				var id = $.trim($("#did").val());
				if(id != "" && id != null && id != 'undefined'){
					var url = '${pageContext.request.contextPath}/handleRegister/update.do';
					title = "修改";
				}
				$.ajax({
					url : url,
					data: formData,
					cache : false,
					type : "post",
					success: function (data) {
	                    if (data >= 1) {
	                        toastr.success(title+'成功');
	                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                            window.location.reload();
	                            $("#reset").click();
	                        },1000);
	                    } else {
	                        toastr.error(title+'失败');
	                    }
	                },
				})
				layer.close(index);
				return false;
			});

			

			/**
			 * 新增表单校验
			 */
			form.verify({
				//value：表单的值、item：表单的DOM对象
	            required: function(value, item){
	            	value = $.trim(value)
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }
	            },
	          //value：表单的值、item：表单的DOM对象 金额
	            money: function(value, item){
	            	value = $.trim(value)
	            	var patrn = /^\d+(\.\d+)?$/;
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }else if(!patrn.test(value)){
	                	return "请输入正确的金额";
	                }
	            },
				//value：表单的值、item：表单的DOM对象
	            only: function(value, item){
	            	value = $.trim(value)
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }else{
	                    var flg = false;
	                    $.ajax({
	                        type:'post',
	                        data:'invoiceNumber='+value,
	                        url:'${pageContext.request.contextPath}/handleRegister/queryAllByMution.do',
	                        dataType: 'JSON',
	                        async: false,
	                        success:function (data) {
	                            if(data.length == 0){
	                                flg  = true;
	                            }else if(data.length == 1){
	                                var ma = $.trim($("#did").val());
	                                if (ma == data[0].id) {
	                                    flg  = true;
	                                }else{
	                                    flg = false;
	                                }
	                            }else{
	                                flg = false;
	                            }
	
	                        }
	                    });
	                    if(!flg){
	                        return '发票号不能重复';
	                    }
	                }
	            }
			});

			laydate.render({
                elem: '#date1'
            });
			
			//增加
            $("#add").click(function(){
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['500px', '350px'] 	//宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                    	$("#id").val("")
	                    $("#payClientId").val("")
	                    $("#money").val("")
	                    $("#remarks").val("")
                        form.render();
                    }
                });
			});

			

          	//批量删除
			$("#dels").click(function(){
				var checkStatus = table.checkStatus('tableList')
	      		var data = checkStatus.data;
	            var idArr = new Array();
	            if(data.length==0){
	                toastr.warning("请至少选择一条记录！");
	            }else{
	            	
	                var names = "";
	                var ids = "";
	                for(var i=0;i<data.length;i++){
	                    if(ids == ""){
	                        ids += data[i].id;
	                    }else{
		                        ids += "," + data[i].id;
	                    }
	                }
	                
	                
	                layer.confirm(names+'确定删除吗？', function(index){
	                    $.ajax({
	                        type:'post',
	                        url:'${pageContext.request.contextPath }/handle/delete.do',
	                        data:{"ids":ids},
	                        success:function(data){
	                            if(data>0){
	                                toastr.success("删除成功！");
	                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                                    //关闭模态框
	                                    // 父页面刷新
	                                    window.location.reload();
	                                },2000);
	                            }else{
	                                toastr.warning("删除失败！");
	                            }
	                        }

	                    })
	                    layer.closeAll();
	                });
	            }
			});
			laydate.render({
                elem: '#createDate'
            });
			  
		});
		
		
		//获取当前时间生成的编码
	   	function curentTimeNumber() {
	   		var now=new Date();
	   		var year = now.getFullYear();       //年
	   	    var month = now.getMonth() + 1;     //月
	   	    var day = now.getDate();            //日
	   	 	var hours = now.getHours(); //获取当前小时数(0-23)
		   	var minutes = now.getMinutes(); //获取当前分钟数(0-59)
		   	var seconds = now.getSeconds(); //获取当前秒数(0-59)
	   	    //var mill=now.getMilliseconds();
	   	    var time=year+""+add0(month)+""+add0(day)+""+add0(hours)+""+add0(minutes)+""+add0(seconds);
	   		return time;
	   	}
	    //获取当前日期
	   	function curentTime(time) {
	   		var now=new Date();
	    	if(time != null && time != ""){
		   		now=new Date(time);
	    	}
	   		var year = now.getFullYear();       //年
	   	    var month = now.getMonth() + 1;     //月
	   	    var day = now.getDate();            //日
	   	    var time=year+"-"+add0(month)+"-"+add0(day);
	   		return time;
	   	}
	   	function add0(m){return m<10?'0'+m:m }
		toastrStyle()
	</script>
</body>
</html>